/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.runtime.jxls;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.vos.ReportVo;
import org.apache.commons.lang3.math.NumberUtils;
import org.jxls.common.Context;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/17 10:09
 * @Modified By:
 */
class FromTaskReportHandler extends AbstractJxlsReportHandler<String> {

    @Override
    Context createContext(CommandContext cc, ReportVo rv, String from) {
        WorkflowContext ctx = cc.getWorkflowContext();
        if (NumberUtils.isNumber(from)) {
            int layer = NumberUtils.toInt(rv.getFrom());
            return create(ctx, ctx.getRecordContext(layer), layer);
        } else if (rv.getFrom().indexOf("->") > 0) {
            // 分层下的EMBBED数据源
            int pos = rv.getFrom().indexOf("->");
            int layer = NumberUtils.toInt(rv.getFrom().substring(0,
                    pos));
            String cid = rv.getFrom().substring(pos + 2);
            String id = ctx.getTask(layer, cid);
            if (id == null)
                throw new EasyPlatformWithLabelKeyException(
                        "task.not.found.from.layer", layer, id);
            WorkflowContext wc = cc.getWorkflowContext(id);
            if (wc == null)
                throw new EasyPlatformWithLabelKeyException(
                        "task.not.found.from.layer", layer, id);
            return create(wc, wc.getRecord(), layer);
        } else {// 当前层下的EMBBED数据源
            String id = ctx.getTask(rv.getFrom());
            if (id == null)
                throw new EasyPlatformWithLabelKeyException(
                        "task.not.found.from.layer",
                        ctx.getParameter("828"), id);
            WorkflowContext wc = cc.getWorkflowContext(id);
            if (wc == null)
                throw new EasyPlatformWithLabelKeyException(
                        "task.not.found.from.layer",
                        ctx.getParameter("828"), id);
            return create(wc, wc.getRecord(), 0);
        }
    }
}
